package com.example.restatr.Atcivity.Bus;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.restatr.Atcivity.Main.MainActivity;
import com.example.restatr.Atcivity.Bus.Bean.BusLineBean;
import com.example.restatr.Atcivity.Bus.Bean.BusStopBean;
import com.example.restatr.R;
import com.example.restatr.Tools;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class BusAt extends AppCompatActivity {
    private Toolbar toolbar;
    private TextView barTitle;
    private EditText search;
    private TextView first;
    private Spinner spinner;
    private TextView end;
    private TextView price;
    private TextView mileage;
    private RecyclerView horizontalRV;
    private List<BusLineBean.RowsBean> busLineRows = new ArrayList<>();
    private List<BusStopBean.RowsBean> busStopRows = new ArrayList<>();
    private int pos;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bus_at);

        toolbar = findViewById(R.id.toolbar);
        barTitle = findViewById(R.id.bar_Title);
        search = findViewById(R.id.search);
        first = findViewById(R.id.first);
        spinner = findViewById(R.id.spinner);
        end = findViewById(R.id.end);
        price = findViewById(R.id.price);
        mileage = findViewById(R.id.mileage);
        horizontalRV = findViewById(R.id.horizontal_RV);

        Tools.SetBarTitle(toolbar, barTitle, "智慧巴士", search, this,true);
        Menu menu = toolbar.getMenu();
        MenuItem item = menu.getItem(0);
        menu.removeItem(R.id.item2);
        item.setTitle("订单列表");
        item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                startActivity(new Intent(BusAt.this, BusOrderAt.class));
                return true;
            }
        });
        horizontalRV.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        spinner.setDropDownVerticalOffset(50);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                first.setText("起始站：" + busLineRows.get(position).getFirst() + "\n首发时间：" + busLineRows.get(position).getStartTime());
                end.setText("终点站：" + busLineRows.get(position).getEnd() + "\n末发时间：" + busLineRows.get(position).getEndTime());
                price.setText("票价：" + busLineRows.get(position).getPrice() + "元");
                mileage.setText("里程：" + busLineRows.get(position).getMileage());
                pos = position;
                GetBusStop(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        GetBusLine();
    }

    private void GetBusStop(int pos) {
        busStopRows.clear();
        new Thread(() -> {
            String get = Tools.Get("/prod-api/api/bus/stop/list?linesId=" + busLineRows.get(pos).getId(), "");
            BusStopBean busStopBean = new Gson().fromJson(get, BusStopBean.class);
            busStopRows.addAll(busStopBean.getRows());
            runOnUiThread(() -> {
                if (busStopRows.size() > 0) {
                    horizontalRV.setAdapter(new busStopAdapter());
                }
            });
        }).start();
    }

    private void GetBusLine() {
        new Thread(() -> {
            String get = Tools.Get("/prod-api/api/bus/line/list", "");
            BusLineBean busLineBean = new Gson().fromJson(get, BusLineBean.class);
            busLineRows.addAll(busLineBean.getRows());
            runOnUiThread(() -> {
                if (busLineRows.size() > 0) {
                    spinner.setAdapter(new spinnerAdapter());
                }
            });
        }).start();
    }

    public void onClick(View view) {
        new Thread(() -> {
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("start", busLineRows.get(pos).getFirst());
                jsonObject.put("end", busLineRows.get(pos).getEnd());
                jsonObject.put("price", busLineRows.get(pos).getPrice());
                jsonObject.put("path", busLineRows.get(pos).getName());
                String post = Tools.Post("/prod-api/api/bus/order", MainActivity.sp.getString("token", ""), jsonObject.toString());
                JSONObject jx = new JSONObject(post);
                int code = jx.getInt("code");
                String msg = jx.getString("msg");
                if (code == 200) {
                    String orderNum = jx.getString("orderNum");
                    JSONObject payJSONObject = new JSONObject();
                    payJSONObject.put("orderNum", orderNum);
                    payJSONObject.put("paymentType", "电子支付");
                    String pay = Tools.Post("/prod-api/api/bus/pay", MainActivity.sp.getString("token", ""), payJSONObject.toString());
                    JSONObject payJx = new JSONObject(pay);
                    String payMsg = payJx.getString("msg");
                    int payCode = payJx.getInt("code");
                    runOnUiThread(() -> {
                        Toast.makeText(this, payMsg, Toast.LENGTH_SHORT).show();
                    });
                } else {
                    Looper.prepare();
                    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
                    Looper.loop();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }).start();
    }

    class spinnerAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return busLineRows.size();
        }

        @Override
        public Object getItem(int position) {
            return busLineRows.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = getLayoutInflater().inflate(R.layout.bus_spinner_item, null);
            TextView text = convertView.findViewById(R.id.text);
            text.setText(busLineRows.get(position).getName());

            return convertView;
        }
    }

    class busStopAdapter extends RecyclerView.Adapter<busStopAdapter.bustStopViewHolder> {

        @NonNull
        @Override
        public bustStopViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View inflate = getLayoutInflater().inflate(R.layout.bus_stop_item_layout, parent, false);
            return new bustStopViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull bustStopViewHolder holder, int position) {
            holder.stopName.setText(busStopRows.get(position).getName());
        }

        @Override
        public int getItemCount() {
            return busStopRows.size();
        }

        class bustStopViewHolder extends RecyclerView.ViewHolder {
            private View line;
            private View oval;
            private TextView stopName;

            public bustStopViewHolder(@NonNull View itemView) {
                super(itemView);
                line = itemView.findViewById(R.id.line);
                oval = itemView.findViewById(R.id.oval);
                stopName = itemView.findViewById(R.id.stopName);
            }
        }
    }
}